package com.quan.weixin.web.handler;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.quan.base.common.utils.SpringContextHolder;
import com.quan.base.common.utils.XmlUtils;
import com.quan.base.common.utils.date.DateUtils;
import com.quan.weixin.WeixinConstant;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.model.BaseMsg;
import com.quan.weixin.model.TextMessage;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.rpc.api.WeixinApiService;
import com.quan.weixin.rpc.api.WeixinMsgService;
import com.quan.weixin.rpc.api.WeixinSubscribeUserService;
import com.quan.weixin.rpc.model.WeixinSubscribeUser;


public class WeixinRequestHandler {

	private static Logger logger = LoggerFactory.getLogger(WeixinRequestHandler.class);

	public static String processRequest(HttpServletRequest request) {
		logger.debug("收到微信请求：" + DateUtils.getDateTime());
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "没有找到你想要的信息...";
			
			// xml请求解析
			Map<String, String> requestMap = XmlUtils.parseXml(request.getInputStream()) ;

			//将Map转换成对象
			BaseMsg baseMsg = JSON.parseObject(JSON.toJSONString(requestMap), BaseMsg.class) ;

			logger.debug("消息类型：" + baseMsg.getMsgType());
			logger.debug("消息内容：" + baseMsg.getContent());
			logger.debug("事件类型：" + baseMsg.getEvent());
			logger.debug("消息JSON：" + baseMsg);
			
			WeixinApiService apiService = SpringContextHolder.getBean(WeixinApiService.class) ;
			WeixinSubscribeUserService subscribeUserService = SpringContextHolder.getBean(WeixinSubscribeUserService.class);
			
			WeixinMsgService weixinMsgService = SpringContextHolder.getBean(WeixinMsgService.class) ;
			
			// 文本消息
			if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_TEXT)) {
				Object textKeyWordHandler = weixinMsgService.textKeyWordHandler(baseMsg) ;
				if(null != textKeyWordHandler) {
					String beanToXml = XmlUtils.beanToXml(textKeyWordHandler) ;
					logger.debug("\r\n{}",beanToXml);
					return beanToXml ;
				}
			}
			// 图片消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！" ;
			}
			// 地理位置消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！坐标（X："+requestMap.get("Location_X")+"，Y："+requestMap.get("Location_Y")+"）地址：" + requestMap.get("Label") ;
			}
			// 链接消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_EVENT)) {
				// 自定义菜单点击事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_CLICK)) {
					Object clickEventHandler = weixinMsgService.clickEventHandler(baseMsg) ;
					if(null != clickEventHandler) {
						String beanToXml = XmlUtils.beanToXml(clickEventHandler) ;
						logger.debug("\r\n{}",beanToXml);
						return beanToXml ;
					}
				}
				
				//获取地理位置
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
					respContent = "";
				}
				
				// 扫码推事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_PUSH)) {
					respContent = "扫码推事件";
				}

				// 扫码推事件且弹出“消息接收中”
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_WAITMSG)) {
					respContent = "扫描后返回结果给用户";
				}

				// 订阅（关注）
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SUBSCRIBE)) {
					//获取关注用户信息
					UserDetail userDetail = apiService.getUserDetail(WeixinContext.getAccessToken(), baseMsg.getFromUserName()) ;
					System.out.println(userDetail);
					
					//保存关注用户信息
					WeixinSubscribeUser subscribeUser = new WeixinSubscribeUser() ;
					BeanUtils.copyProperties(userDetail, subscribeUser);
					subscribeUser.setSubscribeTime(userDetail.getSubscribe_time());
					subscribeUser.setTagidList(JSON.toJSONString(userDetail.getTagid_list()));
					subscribeUser.setHeadimgurl(userDetail.getHeadimgurl() != null ? userDetail.getHeadimgurl().replaceAll("/132", "/46") : null);
					subscribeUserService.insertSelective(subscribeUser);
					logger.info("用户关注了公众号，openid:" + baseMsg.getFromUserName());
					
					String beanToXml = XmlUtils.beanToXml(weixinMsgService.subscribeHandler(baseMsg));
					logger.debug("\r\n{}",beanToXml);
					
					return beanToXml ;
				}
				// 取消订阅（取消关注）
				else if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
					subscribeUserService.deleteByOpenId(baseMsg.getFromUserName());
					logger.info("用户取消关注："+baseMsg.getFromUserName());
				}
			}
			
			/*System.out.println("====================================回复内容===================================");
			
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setFromUserName(baseMsg.getToUserName());
			textMessage.setToUserName(baseMsg.getFromUserName());
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(WeixinConstant.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(respContent);
			respMessage = XmlUtils.beanToXml(textMessage) ;
			logger.debug("\r\n{}",respMessage);*/

		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

}
